//
//  EpointWebInfoListViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 14-1-17.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointWebInfoListViewController.h"
#import "EpointWebInfoModel.h"
#import "EpointWebInfoListCell.h"
#import "MJRefresh.h"
#import "EpointWebInfoDetailViewController.h"
#import "EpointWebInfoDetailViewController_V2.h"
#import "EpointWebInfoListCellUniversalCell.h"

@interface EpointWebInfoListViewController ()
{
    NSMutableArray *dataArray;
    UITableView *tv;
    UISearchBar *sb;
    UISearchDisplayController *searchController;
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
    //列表索引
    int pageIndex;
    
    //每页列表数量
    int listPageCount;
    
    //搜索关键字
    NSString *keyWork;
}
@end

@implementation EpointWebInfoListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    pageIndex = 1;
    listPageCount = 20;
    keyWork = @"";
    
    dataArray = [[NSMutableArray alloc]init];
    sb = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 44)];
    sb.placeholder = @"关键字检索";
    sb.delegate = self;
    [self.view addSubview:sb];
    
    
    searchController = [[UISearchDisplayController alloc]initWithSearchBar:sb contentsController:self];
    searchController.searchResultsTableView.backgroundColor = [UIColor clearColor];
    searchController.searchResultsTableView.separatorColor = [UIColor clearColor];
    searchController.delegate = self;
    searchController.searchResultsDataSource = self;
    searchController.searchResultsDelegate = self;
    searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    searchController.searchResultsTableView.bounces = NO;
    
    tv = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, AppWidth, AppHeight-SystemTakeHeight-44)];
    tv.rowHeight = 75;
    tv.dataSource = self;
    tv.delegate = self;
//    tv.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tv];
    
    [self getData:pageIndex taskid:1];
    [self addHeader];
    [self addFooter];
}

- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell {
    return YES;
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:NO];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:YES];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [dataArray removeAllObjects];
    pageIndex = 1;
    keyWork = searchText;
    [self getData:pageIndex taskid:1];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    [searchBar resignFirstResponder];
    
    [searchController setActive:NO animated:YES];
}

- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = tv;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        pageIndex++;
        [self getData:pageIndex taskid:1];
    };
    _footer = footer;
}

-(void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = tv;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self getData:1 taskid:2];
    };
    _header = header;
}

-(void)getData:(int)_index taskid:(int)taskid
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:[NSString stringWithFormat:@"%i",listPageCount] forKey:@"pagesize"];
    [params setObject:keyWork forKey:@"keyword"];
    [params setObject:[self.passParam objectForKey:@"categoryguid"] forKey:@"categoryguid"];
    [params setObject:[NSString stringWithFormat:@"%i",_index] forKey:@"CurrentPageIndex"];
    [self startTask:@"WebInfo_GetView_Task" withParams:params withTaskId:taskid];
}

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    //处理异常信息
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
        [self toastMessage:[arr objectAtIndex:1]];
        [_footer endRefreshing];
        [_header endRefreshing];
        return;
    }
    
    if (taskId==1) {
        
        NSMutableArray *listData = [arr objectAtIndex:2];
        
        for (EpointWebInfoModel *m in listData) {
            [dataArray addObject:m];
        }
        [tv reloadData];
        [searchController.searchResultsTableView reloadData];
        [_footer endRefreshing];
        if (listData.count<listPageCount&&keyWork.length==0) {
            [_footer removeFromSuperview];
        }
    }
    else if (taskId==2)
    {
        NSMutableArray *listData = [arr objectAtIndex:2];
        NSMutableArray *enableData = [[NSMutableArray alloc]init];
        for (EpointWebInfoModel *m in listData) {
            EpointWebInfoModel *om = [dataArray objectAtIndex:0];
            NSString *firstInfoGuid = om.InfoGuid;
            if ([m.InfoGuid isEqualToString:firstInfoGuid]) {
                break;
            }
            else
            {
                [enableData addObject:m];
            }
        }
        for (int i=enableData.count-1; i>=0; i--) {
            EpointWebInfoModel *sm = [enableData objectAtIndex:i];
            [dataArray insertObject:sm atIndex:0];
        }
        [_header endRefreshing];
        [tv reloadData];
    }
    [self homeToDetail];
}

-(void)homeToDetail{
    if (XAppDelegate.clickItemPos!=-1) {
        EpointWebInfoModel *m = [dataArray objectAtIndex:XAppDelegate.clickItemPos];
        m.IsRead = @"1";
        [dataArray setObject:m atIndexedSubscript:XAppDelegate.clickItemPos];
        XAppDelegate.clickItemPos=-1;
        [tv reloadData];
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:[self.passParam objectForKey:@"categoryguid"] forKey:@"CategoryGuid"];
        [params setObject:m.InfoGuid forKey:@"InfoGuid"];
        [params setObject:m.Content forKey:@"Content"];
        [params setObject:@"信息详情" forKey:@"title"];
        EpointWebInfoDetailViewController_V2 *wi = [[EpointWebInfoDetailViewController_V2 alloc]init];
        wi.passParam = params;
        [self.navigationController pushViewController:wi animated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *WebinfolistItem = @"EpointWebInfoListCellUniversalCell";
    EpointWebInfoListCellUniversalCell *cell = (EpointWebInfoListCellUniversalCell *)[tableView dequeueReusableCellWithIdentifier:WebinfolistItem];
    
    if (cell == nil) {
        
        cell = [[EpointWebInfoListCellUniversalCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:WebinfolistItem
                                  containingTableView:tableView // Used for row height and selection
                                   leftUtilityButtons:nil
                                  rightUtilityButtons:[self rightButtons]];
        cell.delegate = self;
    }
    
    EpointWebInfoModel *m = [dataArray objectAtIndex:indexPath.row];
    cell.lbTitle.text = m.txtTitle;
    
    cell.lbPerson.text = [[[m.PostDate componentsSeparatedByString:@" "]objectAtIndex:0]stringByReplacingOccurrencesOfString:@"/" withString:@"."];
    cell.lbFeedBack.text = [NSString stringWithFormat:@"%@ 回复",m.FeedBackCount];
    
    if ([m.IsRead isEqualToString:@"1"]) {
        cell.ivStatus.hidden = YES;
        [cell.lbTitle setFrame:CGRectMake(7, 3, AppWidth-14, 45)];
        
    }
    else
    {
        cell.ivStatus.hidden = NO;
        [cell.lbTitle setFrame:CGRectMake(cell.ivStatus.frame.origin.x+cell.ivStatus.frame.size.width+5,3, AppWidth-20, 45)];
    }
    
    if ([m.HasAttach isEqualToString:@"1"]) {
        cell.lbAttach.hidden = NO;
        cell.lbFeedBack.frame = CGRectMake(AppWidth/2-7, 49, AppWidth-cell.lbPerson.frame.size.width-cell.lbAttach.frame.size.width-10, 20);
    }
    else
    {
        cell.lbAttach.hidden = YES;
        cell.lbFeedBack.frame = CGRectMake(AppWidth/2-7, 49, AppWidth-cell.lbPerson.frame.size.width-10, 20);
    }
    
    if ([m.FeedBackCount integerValue]==0) {
        cell.lbFeedBack.hidden = YES;
    }
    else
    {
        cell.lbFeedBack.hidden = NO;
    }
    
    return cell;
}

- (NSArray *)rightButtons
{
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                title:@"收藏"];
    return rightUtilityButtons;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EpointWebInfoModel *m = [dataArray objectAtIndex:indexPath.row];
    m.IsRead = @"1";
    [dataArray setObject:m atIndexedSubscript:indexPath.row];
    [tv reloadData];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:[self.passParam objectForKey:@"categoryguid"] forKey:@"CategoryGuid"];
    [params setObject:m.InfoGuid forKey:@"InfoGuid"];
    [params setObject:m.Content forKey:@"Content"];
    [params setObject:@"信息详情" forKey:@"title"];
    EpointWebInfoDetailViewController_V2 *wi = [[EpointWebInfoDetailViewController_V2 alloc]init];
    wi.passParam = params;
    [self.navigationController pushViewController:wi animated:YES];
}

@end
